package com.ideabove.util.img;

import java.lang.ref.WeakReference;

import com.ideabove.radio.R;
import com.tekle.oss.android.animation.AnimationFactory;

import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;


public class BitmapDownloaderTask extends AsyncTask<String, Void, Bitmap> {
	private final WeakReference<ImageView> imageViewReference;
	private int cropType = 0;
	public String url;
	
	public static int CROP_NO = 0;
	public static int CROP_CENTER = 1;

	public BitmapDownloaderTask(ImageView imageView, int cropType) {
		this.cropType = cropType;
		imageViewReference = new WeakReference<ImageView>(imageView);
		
	}

	@Override
	// Actual download method, run in the task thread
	protected Bitmap doInBackground(String... params) {
		// params comes from the execute() call: params[0] is the url.
		this.url = params[0];
		return ImageLoader.downloadBitmap(params[0]);		
	}

	@Override
	// Once the image is downloaded, associates it to the imageView
	protected void onPostExecute(Bitmap bitmap) {
		if (isCancelled()) {
			bitmap = null;
		}
		
		if(imageViewReference != null && bitmap == null){
			ImageView imageView = imageViewReference.get();
			
			if(imageView != null){
				imageView.setImageResource(R.drawable.black);
				imageView.setScaleType(ScaleType.FIT_XY);
			}
			return;
		}
		
		if (imageViewReference != null && cropType == CROP_NO) {			

			ImageView imageView = imageViewReference.get();
		    BitmapDownloaderTask bitmapDownloaderTask = ImageLoader.getBitmapDownloaderTask(imageView);
		    // Change bitmap only if this process is still associated with it
		    if (this == bitmapDownloaderTask) {
		        imageView.setImageBitmap(bitmap);
		    }
			
		}else if(imageViewReference != null && cropType == CROP_CENTER){
			ImageView imageView = imageViewReference.get();
			
		    BitmapDownloaderTask bitmapDownloaderTask = ImageLoader.getBitmapDownloaderTask(imageView);
		    // Change bitmap only if this process is still associated with it
		    if (this == bitmapDownloaderTask) {
		    	bitmap = ImageLoader.cropCenter(bitmap, imageView.getWidth(), imageView.getHeight());
				
				if (imageView != null) {
					imageView.setImageBitmap(bitmap);
					ImageLoader.mCache.put(url, bitmap);
				}
		    }
			
		}
		
		
	}
}
